//
//  calendarVC.swift
//  movieInfo
//
//  Created by zhangkai on 2023/5/14.
//

import UIKit
import FSCalendar
class calendarVC: UIViewController,FSCalendarDelegate,FSCalendarDataSource,UITableViewDelegate,UITableViewDataSource {

    
    var tableView:UITableView!
    var arr:[Movie] = []

    
    fileprivate let gregorian: NSCalendar! = NSCalendar(calendarIdentifier:NSCalendar.Identifier.gregorian)
    
    var calendar = FSCalendar(frame: CGRect(x: 0, y: 0, width: 320, height: 300))
    
    fileprivate let formatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy/MM/dd"
        return formatter
    }()

    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        calendar.reloadData()
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        view.backgroundColor = .white
        
        
        calendar.dataSource = self
        calendar.delegate = self
        view.addSubview(calendar)
        calendar.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
//            make.top.equalTo(view.safeAreaInsets.bottom)
            make.top.equalTo(topLayoutGuide.snp.bottom)
            make.height.equalTo(300)
        }
        
        

        
        
        tableView = UITableView(frame: CGRectZero, style: .plain)
        tableView.register(searchViewVCCell.self, forCellReuseIdentifier: "searchViewVCCell")

        tableView.backgroundColor = .secondarySystemBackground
        tableView.rowHeight = 190
        tableView.estimatedSectionFooterHeight = 0.01
        tableView.estimatedSectionHeaderHeight = 0.01
        tableView.tableFooterView = UIView()
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.delegate = self
        tableView.dataSource = self
//        tableView.isHidden = true
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in

            make.top.equalTo(calendar.snp.bottom).offset(0)
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        
        
        
//        self.calendar = calendar
        
        
    }
    
    func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
        
        let str = self.formatter.string(from: date)
        var temparr:[Movie] = []
        if let data = UserDefaults.standard.value(forKey: "savefvolist") as? Data {
            let copy = try? PropertyListDecoder().decode([Movie].self, from: data)
//            arr = copy!

            for i in 0..<copy!.count{
                let model = copy![i]
                if model.saveTime == str{
                    temparr.append(model)
                }
            }
            
            arr = temparr
            self.tableView.reloadData()

        }else{
            arr = []
            self.tableView.reloadData()
        }
        
        
    }
    
    
    
    func calendar(_ calendar: FSCalendar, imageFor date: Date) -> UIImage? {

        if let data = UserDefaults.standard.value(forKey: "savefvolist") as? Data {
            let copy = try? PropertyListDecoder().decode([Movie].self, from: data)
//            arr = copy!
            let str = self.formatter.string(from: date)
            let str1 = self.formatter.string(from: Date())
            var dateArr:[String] = []
            var temparr:[Movie] = []
            for i in 0..<copy!.count{
                let model = copy![i]
                dateArr.append(model.saveTime ?? "")
                
                
//                let model = copy![i]
                if model.saveTime == str1{
                    temparr.append(model)
                }
                
                
            }
            
            arr = temparr
            self.tableView.reloadData()
            
            
            

            return dateArr.contains(str) ? UIImage(named: "icon_cat") : nil
           
        }else{
            arr = []
            self.tableView.reloadData()
            
            return nil
        }
        
       
        
        
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return arr.count
        
       
   }
   
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell:searchViewVCCell = tableView.dequeueReusableCell(withIdentifier: "searchViewVCCell") as? searchViewVCCell ?? searchViewVCCell()
        cell.selectionStyle = .none

        if let path = self.arr[indexPath.row].posterPath {
            cell.img.downloadImage(fromPath: path)
        }
        cell.nameLabel.text = self.arr[indexPath.row].title ?? ""
        cell.stattLabel.text = "\(self.arr[indexPath.row].voteAverage ?? 0.0)"
        cell.infoLabel.text = self.arr[indexPath.row].overview ?? ""
        
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let movieInfo = self.arr[indexPath.row]
        let destVC = ViewControllerInfoVC()
        destVC.model = movieInfo
        self.navigationController?.pushViewController(destVC, animated: true)
        
        
    }

}
